<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="关键词搜索">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索订单号、客户姓名、电话"
            clearable
            style="width: 250px"
            @input="handleSearch"
            @keyup.enter="handleQuery"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="订单号">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入订单号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="客户手机">
          <el-input
            v-model="queryParams.customerPhone"
            placeholder="请输入客户手机号"
            clearable
            style="width: 180px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input
            v-model="queryParams.customerName"
            placeholder="请输入客户姓名"
            clearable
            style="width: 150px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option
              v-for="[status, info] in Object.entries(statusMap)"
              :key="status"
              :label="info.text"
              :value="status"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型">
          <el-select v-model="queryParams.serviceType" placeholder="请选择服务类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="精洗套装" value="精洗套装" />
            <el-option label="普通清洗" value="普通清洗" />
            <el-option label="干洗" value="干洗" />
            <el-option label="快洗" value="快洗" />
            <el-option label="洗鞋" value="洗鞋" />
            <el-option label="洗萌宠" value="洗萌宠" />
            <el-option label="洗包包" value="洗包包" />
            <el-option label="洗被子" value="洗被子" />
            <el-option label="洗车" value="洗车" />
            <el-option label="上门清洗" value="上门清洗" />
            <el-option label="疏通厕所" value="疏通厕所" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :icon="Search">查询</el-button>
          <el-button @click="resetQuery" :icon="Refresh">重置</el-button>
          <el-button @click="showAdvancedFilter">高级筛选</el-button>
          <el-button type="success" @click="exportOrders" :icon="Download">导出</el-button>
          <el-button type="info" @click="refreshList" :icon="Refresh">刷新</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作栏 -->
      <div v-if="selectedOrders.length > 0" class="batch-operations">
        <span class="batch-info">已选择 {{ selectedOrders.length }} 个订单</span>
        <el-button type="primary" size="small" @click="batchUpdateStatus">批量更新状态</el-button>
        <el-button type="danger" size="small" @click="handleBatchCancelOrders">批量取消</el-button>
        <el-button type="success" size="small" @click="handleBatchExportOrders">批量导出</el-button>
      </div>
    </el-card>

    <!-- 订单统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card pending clickable" @click="showOrderAnalysis('pending')">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ orderStats.pending }}</div>
              <div class="stat-label">待接单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card processing clickable" @click="showOrderAnalysis('processing')">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Loading /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ orderStats.processing }}</div>
              <div class="stat-label">进行中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card completed clickable" @click="showOrderAnalysis('completed')">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ orderStats.completed }}</div>
              <div class="stat-label">已完成</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card urgent clickable" @click="showOrderAnalysis('urgent')">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ orderStats.urgent }}</div>
              <div class="stat-label">急需接单</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快速筛选按钮 -->
    <el-card class="quick-filter-container">
      <div class="quick-filter-buttons">
        <el-button
          :type="activeTab === 'all' ? 'primary' : ''"
          @click="setActiveTab('all')"
        >
          全部订单 ({{ orderList.length }})
        </el-button>
        <el-button
          :type="activeTab === ORDER_STATUS.PENDING ? 'warning' : ''"
          @click="setActiveTab(ORDER_STATUS.PENDING)"
        >
          {{ ORDER_STATUS_TEXT[ORDER_STATUS.PENDING] }} ({{ getStatusCount(ORDER_STATUS.PENDING) }})
        </el-button>
        <el-button
          :type="activeTab === ORDER_STATUS.PAID ? 'primary' : ''"
          @click="setActiveTab(ORDER_STATUS.PAID)"
        >
          {{ ORDER_STATUS_TEXT[ORDER_STATUS.PAID] }} ({{ getStatusCount(ORDER_STATUS.PAID) }})
        </el-button>
        <el-button
          :type="activeTab === ORDER_STATUS.SHIPPED ? 'info' : ''"
          @click="setActiveTab(ORDER_STATUS.SHIPPED)"
        >
          {{ ORDER_STATUS_TEXT[ORDER_STATUS.SHIPPED] }} ({{ getStatusCount(ORDER_STATUS.SHIPPED) }})
        </el-button>
        <el-button
          :type="activeTab === ORDER_STATUS.DELIVERED ? 'success' : ''"
          @click="setActiveTab(ORDER_STATUS.DELIVERED)"
        >
          {{ ORDER_STATUS_TEXT[ORDER_STATUS.DELIVERED] }} ({{ getStatusCount(ORDER_STATUS.DELIVERED) }})
        </el-button>
        <el-button
          :type="activeTab === ORDER_STATUS.FINISHED ? 'success' : ''"
          @click="setActiveTab(ORDER_STATUS.FINISHED)"
        >
          {{ ORDER_STATUS_TEXT[ORDER_STATUS.FINISHED] }} ({{ getStatusCount(ORDER_STATUS.FINISHED) }})
        </el-button>
        <el-button
          :type="activeTab === ORDER_STATUS.CANCELLED ? 'danger' : ''"
          @click="setActiveTab(ORDER_STATUS.CANCELLED)"
        >
          {{ ORDER_STATUS_TEXT[ORDER_STATUS.CANCELLED] }} ({{ getStatusCount(ORDER_STATUS.CANCELLED) }})
        </el-button>
      </div>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="tabs-container">
      <div style="margin-top: 32px;">
        <div v-if="filteredOrders.length > 0">
          <!-- 批量操作工具栏 -->
          <div class="batch-toolbar" v-if="selectedOrders.length > 0">
            <div class="toolbar-left">
              <span class="selected-count">已选择 {{ selectedOrders.length }} 个订单</span>
            </div>
            <div class="toolbar-right">
              <el-button-group>
                <el-button size="small" @click="batchUpdateStatus">
                  批量更新状态
                </el-button>
                <el-button size="small" @click="handleBatchCancelOrders">
                  批量取消
                </el-button>
                <el-button size="small" @click="handleBatchExportOrders">
                  批量导出
                </el-button>
                <el-button size="small" @click="clearSelection">
                  清空选择
                </el-button>
              </el-button-group>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="filteredOrders"
            style="width: 100%"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="订单号" prop="orderId" width="140" show-overflow-tooltip>
              <template #default="{ row }">
                <el-button type="text" @click="handleViewDetail(row.orderId)">
                  {{ row.orderId }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="客户信息" width="150">
              <template #default="{ row }">
                <div class="customer-info">
                  <div class="customer-name">{{ row.customerName }}</div>
                  <div class="customer-phone">{{ row.customerPhone }}</div>
                  <div class="customer-address">{{ row.pickupAddress }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="洗护服务" min-width="200">
              <template #default="{ row }">
                <div class="service-info">
                  <div class="service-type">
                    <el-tag size="small" :type="getServiceTypeColor(row.serviceType)">
                      {{ row.serviceType }}
                    </el-tag>
                  </div>
                  <div class="service-items">
                    {{ row.items.join('、') }}
                  </div>
                  <div class="service-note" v-if="row.specialNote">
                    备注: {{ row.specialNote }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="金额" width="100">
              <template #default="{ row }">
                <span class="price">¥{{ row.totalAmount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="距离" width="80">
              <template #default="{ row }">
                <span class="distance">{{ row.distance }}km</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="下单时间" prop="createTime" width="140" />
            <el-table-column label="剩余时间" width="100">
              <template #default="{ row }">
                <span :class="getTimeClass(row.remainingTime)">
                  {{ row.remainingTime }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <!-- 待接单状态 -->
                  <el-button
                    v-if="row.status === ORDER_STATUS.PENDING"
                    type="primary"
                    size="small"
                    @click="handleAcceptOrder(row)"
                  >
                    接单
                  </el-button>
                  <el-button
                    v-if="row.status === ORDER_STATUS.PENDING"
                    type="danger"
                    size="small"
                    @click="handleRejectOrder(row)"
                  >
                    拒绝
                  </el-button>

                  <!-- 已接单状态 - 等待付款 -->
                  <el-button
                    v-if="row.status === ORDER_STATUS.ACCEPTED"
                    type="success"
                    size="small"
                    @click="handleConfirmPayment(row)"
                  >
                    确认付款
                  </el-button>

                  <!-- 已付款状态 - 开始取件 -->
                  <el-button
                    v-if="row.status === ORDER_STATUS.PAID"
                    type="primary"
                    size="small"
                    @click="handleStartPickup(row)"
                  >
                    开始取件
                  </el-button>

                  <!-- 取件中状态 - 确认取件 -->
                  <el-button
                    v-if="row.status === ORDER_STATUS.PICKUP_STARTED"
                    type="success"
                    size="small"
                    @click="handleConfirmPickup(row)"
                  >
                    确认取件
                  </el-button>

                  <!-- 取件完成状态 - 开始洗护 -->
                  <el-button
                    v-if="row.status === ORDER_STATUS.PICKUP_COMPLETED"
                    type="primary"
                    size="small"
                    @click="handleStartProcessing(row)"
                  >
                    开始洗护
                  </el-button>

                  <!-- 洗护中状态 - 完成洗护 -->
                  <el-button
                    v-if="row.status === ORDER_STATUS.PROCESSING"
                    type="success"
                    size="small"
                    @click="handleCompleteProcessing(row)"
                  >
                    完成洗护
                  </el-button>

                  <!-- 质检中状态 - 开始配送 -->
                  <el-button
                    v-if="row.status === ORDER_STATUS.QUALITY_CHECK"
                    type="primary"
                    size="small"
                    @click="handleStartDelivery(row)"
                  >
                    开始配送
                  </el-button>

                  <!-- 配送中状态 - 确认送达 -->
                  <el-button
                    v-if="row.status === ORDER_STATUS.DELIVERY_STARTED"
                    type="success"
                    size="small"
                    @click="handleConfirmDelivery(row)"
                  >
                    确认送达
                  </el-button>

                  <!-- 已送达状态 - 完成订单 -->
                  <el-button
                    v-if="row.status === ORDER_STATUS.DELIVERED"
                    type="warning"
                    size="small"
                    @click="handleCompleteOrder(row)"
                  >
                    完成订单
                  </el-button>

                  <!-- 取消订单按钮 - 只在特定状态下显示 -->
                  <el-button
                    v-if="[ORDER_STATUS.PENDING, ORDER_STATUS.ACCEPTED, ORDER_STATUS.PAID].includes(row.status)"
                    type="danger"
                    size="small"
                    @click="handleCancelOrder(row)"
                  >
                    取消
                  </el-button>

                  <!-- 查看详情按钮 - 始终显示 -->
                  <el-button
                    size="small"
                    @click="handleViewDetail(row.id || row.orderId)"
                  >
                    详情
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-show="total > 0"
              :current-page="queryParams.pageNum"
              :page-size="queryParams.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
        <div v-else class="orders-empty">
          <div v-if="loading">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else>
            暂无订单，再接再厉
          </div>
        </div>
      </div>
    </el-card>
  </div>

  <!-- 发货对话框 -->
  <el-dialog
    v-model="shipDialogVisible"
    title="订单发货"
    width="500px"
    @close="resetShipForm"
  >
    <el-form
      ref="shipFormRef"
      :model="shipForm"
      :rules="shipFormRules"
      label-width="100px"
    >
      <el-form-item label="物流公司" prop="logisticsCompany">
        <el-select v-model="shipForm.logisticsCompany" placeholder="请选择物流公司">
          <el-option label="顺丰速运" value="SF" />
          <el-option label="中通快递" value="ZTO" />
          <el-option label="圆通速递" value="YTO" />
          <el-option label="韵达快递" value="YD" />
          <el-option label="申通快递" value="STO" />
          <el-option label="邮政快递" value="EMS" />
        </el-select>
      </el-form-item>
      <el-form-item label="物流单号" prop="trackingNumber">
        <el-input v-model="shipForm.trackingNumber" placeholder="请输入物流单号" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="shipForm.remark"
          type="textarea"
          placeholder="请输入备注信息（选填）"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="shipSubmitting" @click="submitShipForm">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 订单详情对话框 -->
  <el-dialog
    v-model="orderDetailDialogVisible"
    title="订单详情"
    width="900px"
    top="5vh"
  >
    <div v-if="currentOrderDetail" class="order-detail-content">
      <!-- 订单基本信息 -->
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="detail-card">
            <template #header>
              <span>订单信息</span>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">
                {{ currentOrderDetail.orderNo }}
              </el-descriptions-item>
              <el-descriptions-item label="订单状态">
                <el-tag :type="getStatusType(currentOrderDetail.status)">
                  {{ getStatusText(currentOrderDetail.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="服务类型">
                <el-tag :type="getServiceTypeColor(currentOrderDetail.serviceType)">
                  {{ currentOrderDetail.serviceType }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="订单金额">
                ¥{{ currentOrderDetail.totalAmount || currentOrderDetail.actualAmount }}
              </el-descriptions-item>
              <el-descriptions-item label="下单时间">
                {{ formatDateTime(currentOrderDetail.createTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="预计完成">
                {{ formatDateTime(currentOrderDetail.expectedTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="客户姓名">
                {{ currentOrderDetail.customerName }}
              </el-descriptions-item>
              <el-descriptions-item label="客户电话">
                {{ currentOrderDetail.customerPhone }}
              </el-descriptions-item>
              <el-descriptions-item label="取件地址" :span="2">
                {{ currentOrderDetail.pickupAddress }}
              </el-descriptions-item>
              <el-descriptions-item label="送达地址" :span="2">
                {{ currentOrderDetail.deliveryAddress }}
              </el-descriptions-item>
              <el-descriptions-item label="特殊要求" :span="2">
                {{ currentOrderDetail.specialNote || '无' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="detail-card">
            <template #header>
              <span>订单时间线</span>
            </template>
            <el-timeline>
              <el-timeline-item
                v-for="item in orderTimeline"
                :key="item.id"
                :timestamp="formatDateTime(item.createTime)"
                :type="item.type"
              >
                <h4>{{ item.title }}</h4>
                <p>{{ item.description }}</p>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-col>
      </el-row>

      <!-- 物流信息 -->
      <el-card class="detail-card" style="margin-top: 20px;" v-if="orderLogistics.length > 0">
        <template #header>
          <span>物流信息</span>
        </template>
        <el-timeline>
          <el-timeline-item
            v-for="item in orderLogistics"
            :key="item.id"
            :timestamp="formatDateTime(item.time)"
            type="primary"
          >
            {{ item.description }}
          </el-timeline-item>
        </el-timeline>
      </el-card>

      <!-- 订单备注 -->
      <el-card class="detail-card" style="margin-top: 20px;">
        <template #header>
          <span>订单备注</span>
        </template>
        <el-input
          v-model="orderRemark"
          type="textarea"
          :rows="3"
          placeholder="添加订单备注..."
          @blur="updateRemark"
        />
      </el-card>
    </div>

    <template #footer>
      <el-button @click="orderDetailDialogVisible = false">关闭</el-button>
      <el-button
        v-for="status in getAvailableTransitions(currentOrderDetail?.status)"
        :key="status"
        :type="getTransitionButtonType(status)"
        @click="handleStatusTransition(status)"
      >
        {{ getTransitionButtonText(status) }}
      </el-button>
    </template>
  </el-dialog>

  <!-- 高级筛选对话框 -->
  <el-dialog
    v-model="advancedFilterDialogVisible"
    title="高级筛选"
    width="600px"
  >
    <el-form :model="advancedFilters" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单金额">
            <el-slider
              v-model="advancedFilters.amountRange"
              range
              :min="0"
              :max="1000"
              :step="10"
              show-input
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配送距离">
            <el-slider
              v-model="advancedFilters.distanceRange"
              range
              :min="0"
              :max="50"
              :step="1"
              show-input
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户类型">
            <el-select v-model="advancedFilters.customerType" placeholder="选择客户类型" style="width: 100%;">
              <el-option label="全部" value="" />
              <el-option label="新客户" value="new" />
              <el-option label="老客户" value="old" />
              <el-option label="VIP客户" value="vip" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付方式">
            <el-select v-model="advancedFilters.paymentMethod" placeholder="选择支付方式" style="width: 100%;">
              <el-option label="全部" value="" />
              <el-option label="微信支付" value="wechat" />
              <el-option label="支付宝" value="alipay" />
              <el-option label="现金支付" value="cash" />
              <el-option label="银行卡" value="card" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="紧急程度">
            <el-radio-group v-model="advancedFilters.urgency">
              <el-radio :label="null">全部</el-radio>
              <el-radio label="urgent">紧急</el-radio>
              <el-radio label="normal">普通</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否有备注">
            <el-radio-group v-model="advancedFilters.hasRemark">
              <el-radio :label="null">全部</el-radio>
              <el-radio :label="true">有备注</el-radio>
              <el-radio :label="false">无备注</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="advancedFilters.createTimeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          style="width: 100%;"
        />
      </el-form-item>

      <el-form-item label="地址关键词">
        <el-input
          v-model="advancedFilters.addressKeyword"
          placeholder="输入取件或送达地址关键词"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="resetAdvancedFilters">重置</el-button>
      <el-button @click="advancedFilterDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="applyAdvancedFilters">应用筛选</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Refresh, Search, Download, Clock, Loading, Check, Warning } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getOrdersList,
  getOrderStats,
  getTodayOrders,
  updateOrderStatus,
  cancelOrder,
  batchUpdateOrderStatus,
  batchCancelOrders,
  exportOrdersData,
  getOrderTimeline,
  getOrderLogistics,
  updateOrderRemark,
  getOrderAnalysis,
  getUrgentOrders,
  searchOrders,
  acceptOrder,
  rejectOrder,
  confirmPayment,
  startPickup,
  confirmPickup,
  startProcessing,
  completeProcessing,
  startQualityCheck,
  completeQualityCheck,
  startDelivery,
  confirmDelivery,
  completeOrder,
  requestRefund,
  uploadOrderPhotos,
  getOrderPhotos,
  ORDER_STATUS,
  ORDER_STATUS_TEXT,
  ORDER_STATUS_COLOR,
  ORDER_STATUS_FLOW,
  canTransitionTo,
  getAvailableTransitions,
  SERVICE_TYPES,
  SERVICE_TYPE_TEXT,
  SERVICE_TYPE_COLOR
} from '@/api/orders'

const router = useRouter()
const loading = ref(false)
const orderList = ref([])
const total = ref(0)
const selectedOrders = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderId: '',
  customerPhone: '',
  customerName: '',
  status: '',
  serviceType: '',
  dateRange: []
})

// 搜索关键词
const searchKeyword = ref('')

// 高级筛选相关
const advancedFilterDialogVisible = ref(false)
const advancedFilters = reactive({
  amountRange: [0, 1000],
  distanceRange: [0, 50],
  customerType: '',
  paymentMethod: '',
  urgency: null,
  hasRemark: null,
  createTimeRange: [],
  addressKeyword: ''
})

// 订单标签
const activeTab = ref('all')

// 订单统计
const orderStats = reactive({
  pending: 0,
  processing: 0,
  completed: 0,
  urgent: 0
})

// 洗护订单状态映射（使用后端真实状态）
const statusMap = {
  [ORDER_STATUS.PENDING]: { type: 'warning', text: ORDER_STATUS_TEXT[ORDER_STATUS.PENDING] },
  [ORDER_STATUS.ACCEPTED]: { type: 'primary', text: ORDER_STATUS_TEXT[ORDER_STATUS.ACCEPTED] },
  [ORDER_STATUS.PAID]: { type: 'success', text: ORDER_STATUS_TEXT[ORDER_STATUS.PAID] },
  [ORDER_STATUS.PICKUP_STARTED]: { type: 'primary', text: ORDER_STATUS_TEXT[ORDER_STATUS.PICKUP_STARTED] },
  [ORDER_STATUS.PICKUP_COMPLETED]: { type: 'success', text: ORDER_STATUS_TEXT[ORDER_STATUS.PICKUP_COMPLETED] },
  [ORDER_STATUS.PROCESSING]: { type: 'primary', text: ORDER_STATUS_TEXT[ORDER_STATUS.PROCESSING] },
  [ORDER_STATUS.QUALITY_CHECK]: { type: 'info', text: ORDER_STATUS_TEXT[ORDER_STATUS.QUALITY_CHECK] },
  [ORDER_STATUS.DELIVERY_STARTED]: { type: 'primary', text: ORDER_STATUS_TEXT[ORDER_STATUS.DELIVERY_STARTED] },
  [ORDER_STATUS.DELIVERED]: { type: 'success', text: ORDER_STATUS_TEXT[ORDER_STATUS.DELIVERED] },
  [ORDER_STATUS.COMPLETED]: { type: 'success', text: ORDER_STATUS_TEXT[ORDER_STATUS.COMPLETED] },
  [ORDER_STATUS.CANCELLED]: { type: 'danger', text: ORDER_STATUS_TEXT[ORDER_STATUS.CANCELLED] },
  [ORDER_STATUS.REFUNDED]: { type: 'info', text: ORDER_STATUS_TEXT[ORDER_STATUS.REFUNDED] }
}

// 获取状态类型
const getStatusType = (status) => {
  return statusMap[status]?.type || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status]?.text || status
}

// 获取服务类型颜色
const getServiceTypeColor = (serviceType) => {
  // 如果是枚举值，使用预定义的颜色
  if (SERVICE_TYPE_COLOR[serviceType]) {
    return SERVICE_TYPE_COLOR[serviceType]
  }

  // 如果是中文名称，映射到对应颜色
  const colorMap = {
    '衣物洗护': 'primary',
    '鞋类护理': 'success',
    '包包清洗': 'warning',
    '床品清洗': 'info',
    '宠物洗护': 'danger',
    '汽车清洗': 'primary',
    '家庭清洁': 'success',
    '管道疏通': 'warning',
    '精洗套装': 'primary',
    '普通清洗': 'success',
    '干洗': 'warning',
    '快洗': 'info',
    '特殊护理': 'danger'
  }
  return colorMap[serviceType] || 'info'
}

// 获取时间样式
const getTimeClass = (time) => {
  if (time.includes('分钟')) {
    const minutes = parseInt(time)
    if (minutes <= 10) return 'time-urgent'
    if (minutes <= 30) return 'time-warning'
  }
  return 'time-normal'
}

// 过滤后的订单列表
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orderList.value
  }
  return orderList.value.filter(order => order.status === activeTab.value)
})

// 获取指定状态的订单数量
const getStatusCount = (status) => {
  return orderList.value.filter(order => order.status === status).length
}

// 设置活动标签
const setActiveTab = (tab) => {
  activeTab.value = tab
  selectedOrders.value = [] // 清空选择
}

// 获取订单列表
const getOrderList = async () => {
  try {
    loading.value = true
    const params = {
      current: queryParams.pageNum,
      size: queryParams.pageSize,
      orderNo: queryParams.orderId,
      customerPhone: queryParams.customerPhone,
      customerName: queryParams.customerName,
      status: queryParams.status,
      serviceType: queryParams.serviceType,
      startDate: queryParams.dateRange?.[0],
      endDate: queryParams.dateRange?.[1],
      keyword: searchKeyword.value,
      activeTab: activeTab.value !== 'all' ? activeTab.value : undefined
    }

    const response = await getOrdersList(params)
    if (response.code === 200) {
      orderList.value = response.data.records || response.data || []
      total.value = response.data.total || orderList.value.length
    } else {
      throw new Error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error(error.message || '获取订单列表失败')
    orderList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取订单统计数据
const getOrderStatsData = async () => {
  try {
    const response = await getOrderStats()
    if (response.code === 200) {
      const stats = response.data
      orderStats.pending = stats.pending || 0
      orderStats.processing = stats.processing || 0
      orderStats.completed = stats.completed || 0
      orderStats.urgent = stats.urgent || 0
    } else {
      throw new Error(response.message || '获取订单统计失败')
    }
  } catch (error) {
    console.error('获取订单统计失败:', error)
    ElMessage.error(error.message || '获取订单统计失败')
    // 重置为0
    orderStats.pending = 0
    orderStats.processing = 0
    orderStats.completed = 0
    orderStats.urgent = 0
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getOrderList()
}

// 处理搜索
const handleSearch = debounce(() => {
  queryParams.pageNum = 1
  getOrderList()
}, 300)

// 防抖函数
function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 显示高级筛选
const showAdvancedFilter = () => {
  advancedFilterDialogVisible.value = true
}

// 重置高级筛选
const resetAdvancedFilters = () => {
  Object.assign(advancedFilters, {
    amountRange: [0, 1000],
    distanceRange: [0, 50],
    customerType: '',
    paymentMethod: '',
    urgency: null,
    hasRemark: null,
    createTimeRange: [],
    addressKeyword: ''
  })
}

// 应用高级筛选
const applyAdvancedFilters = () => {
  advancedFilterDialogVisible.value = false
  queryParams.pageNum = 1
  getOrderList()
  ElMessage.success('筛选条件已应用')
}

// 批量取消订单
const handleBatchCancelOrders = async () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要取消的订单')
    return
  }

  try {
    const { value: reason } = await ElMessageBox.prompt(
      `确认批量取消 ${selectedOrders.value.length} 个订单？`,
      '批量取消订单',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入取消原因',
        inputValidator: (value) => {
          if (!value || value.trim().length === 0) {
            return '请输入取消原因'
          }
          return true
        }
      }
    )

    const orderIds = selectedOrders.value.map(order => order.id || order.orderId)
    const response = await batchCancelOrders(orderIds, reason)

    if (response.code === 200) {
      ElMessage.success('批量取消成功')
      selectedOrders.value = []
      await getOrderList()
      await getOrderStatsData()
    } else {
      throw new Error(response.message || '批量取消失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量取消失败:', error)
      ElMessage.error(error.message || '批量取消失败')
    }
  }
}

// 批量导出订单
const handleBatchExportOrders = async () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要导出的订单')
    return
  }

  try {
    const orderIds = selectedOrders.value.map(order => order.id || order.orderId)
    const response = await exportOrdersData({ orderIds })

    if (response instanceof Blob) {
      const url = URL.createObjectURL(response)
      const link = document.createElement('a')
      link.href = url
      link.download = `批量订单_${new Date().toISOString().slice(0, 10)}.xlsx`
      link.click()
      URL.revokeObjectURL(url)
      ElMessage.success('批量导出成功')
    } else {
      // 前端生成CSV
      const exportData = selectedOrders.value.map(order => ({
        '订单号': order.orderId || order.orderNo,
        '客户姓名': order.customerName,
        '客户电话': order.customerPhone,
        '服务类型': order.serviceType,
        '订单金额': `¥${order.totalAmount || order.actualAmount}`,
        '订单状态': getStatusText(order.status),
        '下单时间': order.createTime || order.createdTime,
        '取件地址': order.pickupAddress || order.receiverAddress,
        '备注': order.specialNote || order.remark || '无'
      }))

      const headers = Object.keys(exportData[0])
      const csvContent = [
        headers.join(','),
        ...exportData.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
      ].join('\n')

      const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', `批量订单_${new Date().toISOString().slice(0, 10)}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)

      ElMessage.success('批量导出成功')
    }
  } catch (error) {
    console.error('批量导出失败:', error)
    ElMessage.error(error.message || '批量导出失败')
  }
}

// 清空选择
const clearSelection = () => {
  selectedOrders.value = []
}

// 显示订单分析
const showOrderAnalysis = async (type) => {
  try {
    const response = await getOrderAnalysis({ type })
    if (response.code === 200) {
      const analysisData = response.data

      // 显示分析结果
      ElMessageBox.alert(
        `
        <div style="text-align: left;">
          <h3>${getAnalysisTitle(type)}</h3>
          <p><strong>总数量：</strong>${analysisData.total || 0}</p>
          <p><strong>今日新增：</strong>${analysisData.todayNew || 0}</p>
          <p><strong>平均金额：</strong>¥${analysisData.avgAmount || 0}</p>
          <p><strong>总金额：</strong>¥${analysisData.totalAmount || 0}</p>
          ${analysisData.trend ? `<p><strong>趋势：</strong>${analysisData.trend > 0 ? '↗️ 上升' : '↘️ 下降'} ${Math.abs(analysisData.trend)}%</p>` : ''}
        </div>
        `,
        '订单分析',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '查看详细报告',
          cancelButtonText: '关闭',
          showCancelButton: true
        }
      ).then(() => {
        // 跳转到详细分析页面或显示更详细的分析
        ElMessage.info('详细分析功能开发中...')
      }).catch(() => {
        // 用户点击了关闭
      })
    } else {
      throw new Error(response.message || '获取分析数据失败')
    }
  } catch (error) {
    console.error('获取订单分析失败:', error)
    ElMessage.error(error.message || '获取订单分析失败')
  }
}

// 获取分析标题
const getAnalysisTitle = (type) => {
  const titleMap = {
    pending: '待处理订单分析',
    processing: '进行中订单分析',
    completed: '已完成订单分析',
    urgent: '紧急订单分析'
  }
  return titleMap[type] || '订单分析'
}

// 重置查询
const resetQuery = () => {
  queryParams.orderId = ''
  queryParams.customerPhone = ''
  queryParams.customerName = ''
  queryParams.status = ''
  queryParams.serviceType = ''
  queryParams.dateRange = []
  handleQuery()
}

// 刷新列表
const refreshList = () => {
  getOrderList()
}

// 导出订单
const exportOrders = async () => {
  try {
    if (filteredOrders.value.length === 0) {
      ElMessage.warning('暂无订单数据可导出')
      return
    }

    const params = {
      orderNo: queryParams.orderId,
      customerPhone: queryParams.customerPhone,
      customerName: queryParams.customerName,
      status: queryParams.status,
      serviceType: queryParams.serviceType,
      startDate: queryParams.dateRange?.[0],
      endDate: queryParams.dateRange?.[1],
      activeTab: activeTab.value !== 'all' ? activeTab.value : undefined
    }

    const response = await exportOrdersData(params)

    // 如果后端返回文件流
    if (response instanceof Blob) {
      const url = URL.createObjectURL(response)
      const link = document.createElement('a')
      link.href = url
      link.download = `订单列表_${new Date().toISOString().slice(0, 10)}.xlsx`
      link.click()
      URL.revokeObjectURL(url)
      ElMessage.success('订单数据导出成功')
    } else {
      // 如果后端返回数据，前端生成CSV
      const exportData = filteredOrders.value.map(order => ({
        '订单号': order.orderId || order.orderNo,
        '客户姓名': order.customerName,
        '客户电话': order.customerPhone,
        '服务类型': order.serviceType,
        '订单金额': `¥${order.totalAmount || order.actualAmount}`,
        '订单状态': getStatusText(order.status),
        '下单时间': order.createTime || order.createdTime,
        '取件地址': order.pickupAddress || order.receiverAddress,
        '备注': order.specialNote || order.remark || '无'
      }))

      const headers = Object.keys(exportData[0])
      const csvContent = [
        headers.join(','),
        ...exportData.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
      ].join('\n')

      const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', `订单列表_${new Date().toISOString().slice(0, 10)}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)

      ElMessage.success('订单数据导出成功')
    }
  } catch (error) {
    console.error('导出订单失败:', error)
    ElMessage.error(error.message || '导出订单失败')
  }
}

// 查看详情
const handleViewDetail = async (orderId) => {
  try {
    // 从当前列表中找到订单
    const order = orderList.value.find(o => (o.id || o.orderId) === orderId)
    if (order) {
      currentOrderDetail.value = order
      orderRemark.value = order.remark || ''

      // 加载订单时间线
      await loadOrderTimeline(orderId)

      // 加载物流信息（如果订单已发货）
      if ([ORDER_STATUS.SHIPPED, ORDER_STATUS.DELIVERED, ORDER_STATUS.FINISHED].includes(order.status)) {
        await loadOrderLogistics(orderId)
      }

      orderDetailDialogVisible.value = true
    } else {
      ElMessage.error('订单不存在')
    }
  } catch (error) {
    console.error('查看订单详情失败:', error)
    ElMessage.error('查看订单详情失败')
  }
}

// 确认付款
const handleConfirmPayment = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认客户已付款？\n订单号：${order.orderNo}\n订单金额：¥${order.totalAmount || order.actualAmount}`,
      '确认付款',
      {
        confirmButtonText: '确认付款',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const response = await updateOrderStatus(order.id, {
      status: ORDER_STATUS.PAID,
      remark: '商家确认客户已付款'
    })

    if (response.code === 200) {
      order.status = ORDER_STATUS.PAID
      orderStats.pending--
      orderStats.processing++
      ElMessage.success('付款确认成功！')
      await getOrderList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认付款失败:', error)
      ElMessage.error('确认付款失败')
    }
  }
}

// 发货
const handleShipOrder = (order) => {
  currentOrderId.value = order.id || order.orderId
  shipDialogVisible.value = true
}

// 确认送达
const handleConfirmDelivery = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认商品已送达？\n订单号：${order.orderNo}\n收货地址：${order.receiverAddress}`,
      '确认送达',
      {
        confirmButtonText: '确认送达',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    const response = await updateOrderStatus(order.id, {
      status: ORDER_STATUS.DELIVERED,
      remark: '商家确认商品已送达'
    })

    if (response.code === 200) {
      order.status = ORDER_STATUS.DELIVERED
      ElMessage.success('送达确认成功！')
      await getOrderList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认送达失败:', error)
      ElMessage.error('确认送达失败')
    }
  }
}

// 完成订单
const handleFinishOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认完成订单？\n订单号：${order.orderNo}\n完成后订单将进入结算流程`,
      '完成订单',
      {
        confirmButtonText: '确认完成',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    const response = await updateOrderStatus(order.id, {
      status: ORDER_STATUS.FINISHED,
      remark: '订单已完成'
    })

    if (response.code === 200) {
      order.status = ORDER_STATUS.FINISHED
      orderStats.processing--
      orderStats.completed++
      ElMessage.success('订单完成！')
      await getOrderList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成订单失败:', error)
      ElMessage.error('完成订单失败')
    }
  }
}

// 取消订单
const handleCancelOrder = async (order) => {
  try {
    const { value: reason } = await ElMessageBox.prompt(
      `确认取消订单？\n订单号：${order.orderNo}`,
      '取消订单',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入取消原因',
        inputValidator: (value) => {
          if (!value || value.trim().length === 0) {
            return '请输入取消原因'
          }
          return true
        }
      }
    )

    const response = await cancelOrder(order.id, { reason })

    if (response.code === 200) {
      order.status = ORDER_STATUS.CANCELLED
      orderStats.pending > 0 && orderStats.pending--
      ElMessage.success('订单已取消')
      await getOrderList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// ==================== 洗护系统特有的订单操作方法 ====================

// 接受订单
const handleAcceptOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认接受订单？\n订单号：${order.orderNo || order.orderId}\n客户：${order.customerName}`,
      '接受订单',
      {
        confirmButtonText: '确认接受',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const response = await acceptOrder(order.id || order.orderId)

    if (response.code === 200) {
      order.status = ORDER_STATUS.ACCEPTED
      ElMessage.success('订单已接受')
      await getOrderList()
      await getOrderStatsData()
    } else {
      throw new Error(response.message || '接受订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('接受订单失败:', error)
      ElMessage.error(error.message || '接受订单失败')
    }
  }
}

// 拒绝订单
const handleRejectOrder = async (order) => {
  try {
    const { value: reason } = await ElMessageBox.prompt(
      `确认拒绝订单？\n订单号：${order.orderNo || order.orderId}`,
      '拒绝订单',
      {
        confirmButtonText: '确认拒绝',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入拒绝原因',
        inputValidator: (value) => {
          if (!value || value.trim().length === 0) {
            return '请输入拒绝原因'
          }
          return true
        }
      }
    )

    const response = await rejectOrder(order.id || order.orderId, { reason })

    if (response.code === 200) {
      order.status = ORDER_STATUS.CANCELLED
      ElMessage.success('订单已拒绝')
      await getOrderList()
      await getOrderStatsData()
    } else {
      throw new Error(response.message || '拒绝订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('拒绝订单失败:', error)
      ElMessage.error(error.message || '拒绝订单失败')
    }
  }
}

// 开始取件
const handleStartPickup = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认开始取件？\n订单号：${order.orderNo || order.orderId}\n地址：${order.pickupAddress || order.receiverAddress}`,
      '开始取件',
      {
        confirmButtonText: '确认开始',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const response = await startPickup(order.id || order.orderId)

    if (response.code === 200) {
      order.status = ORDER_STATUS.PICKUP_STARTED
      ElMessage.success('已开始取件')
      await getOrderList()
      await getOrderStatsData()
    } else {
      throw new Error(response.message || '开始取件失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始取件失败:', error)
      ElMessage.error(error.message || '开始取件失败')
    }
  }
}

// 确认取件
const handleConfirmPickup = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认已取件？\n订单号：${order.orderNo || order.orderId}`,
      '确认取件',
      {
        confirmButtonText: '确认取件',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    const response = await confirmPickup(order.id || order.orderId)

    if (response.code === 200) {
      order.status = ORDER_STATUS.PICKUP_COMPLETED
      ElMessage.success('取件已确认')
      await getOrderList()
      await getOrderStatsData()
    } else {
      throw new Error(response.message || '确认取件失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认取件失败:', error)
      ElMessage.error(error.message || '确认取件失败')
    }
  }
}

// 开始洗护
const handleStartProcessing = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认开始洗护？\n订单号：${order.orderNo || order.orderId}\n服务类型：${order.serviceType}`,
      '开始洗护',
      {
        confirmButtonText: '确认开始',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const response = await startProcessing(order.id || order.orderId)

    if (response.code === 200) {
      order.status = ORDER_STATUS.PROCESSING
      ElMessage.success('已开始洗护')
      await getOrderList()
      await getOrderStatsData()
    } else {
      throw new Error(response.message || '开始洗护失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始洗护失败:', error)
      ElMessage.error(error.message || '开始洗护失败')
    }
  }
}

// 完成洗护
const handleCompleteProcessing = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认洗护完成？\n订单号：${order.orderNo || order.orderId}`,
      '完成洗护',
      {
        confirmButtonText: '确认完成',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    const response = await completeProcessing(order.id || order.orderId)

    if (response.code === 200) {
      order.status = ORDER_STATUS.QUALITY_CHECK
      ElMessage.success('洗护已完成，进入质检')
      await getOrderList()
      await getOrderStatsData()
    } else {
      throw new Error(response.message || '完成洗护失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成洗护失败:', error)
      ElMessage.error(error.message || '完成洗护失败')
    }
  }
}

// 开始配送
const handleStartDelivery = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认开始配送？\n订单号：${order.orderNo || order.orderId}\n配送地址：${order.deliveryAddress || order.pickupAddress}`,
      '开始配送',
      {
        confirmButtonText: '确认开始',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const response = await startDelivery(order.id || order.orderId)

    if (response.code === 200) {
      order.status = ORDER_STATUS.DELIVERY_STARTED
      ElMessage.success('已开始配送')
      await getOrderList()
      await getOrderStatsData()
    } else {
      throw new Error(response.message || '开始配送失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始配送失败:', error)
      ElMessage.error(error.message || '开始配送失败')
    }
  }
}



// 完成订单
const handleCompleteOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认完成订单？\n订单号：${order.orderNo || order.orderId}`,
      '完成订单',
      {
        confirmButtonText: '确认完成',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    const response = await completeOrder(order.id || order.orderId)

    if (response.code === 200) {
      order.status = ORDER_STATUS.COMPLETED
      ElMessage.success('订单已完成')
      await getOrderList()
      await getOrderStatsData()
    } else {
      throw new Error(response.message || '完成订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成订单失败:', error)
      ElMessage.error(error.message || '完成订单失败')
    }
  }
}



// 选择变化
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection
}

// 批量更新状态
const batchUpdateStatus = async () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要操作的订单')
    return
  }

  try {
    const { value: status } = await ElMessageBox.prompt(
      `确认批量更新 ${selectedOrders.value.length} 个订单的状态？`,
      '批量更新状态',
      {
        confirmButtonText: '确认更新',
        cancelButtonText: '取消',
        inputType: 'select',
        inputOptions: Object.entries(statusMap).map(([key, value]) => ({
          value: key,
          label: value.text
        })),
        inputValidator: (value) => {
          if (!value) {
            return '请选择状态'
          }
          return true
        }
      }
    )

    const orderIds = selectedOrders.value.map(order => order.id || order.orderId)
    const response = await batchUpdateOrderStatus(orderIds, status)

    if (response.code === 200) {
      ElMessage.success('批量更新状态成功')
      selectedOrders.value = []
      await getOrderList()
      await getOrderStatsData()
    } else {
      throw new Error(response.message || '批量更新状态失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量更新状态失败:', error)
      ElMessage.error(error.message || '批量更新状态失败')
    }
  }
}



// 批量导出订单
const batchExportOrders = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要导出的订单')
    return
  }

  try {
    // 准备导出数据
    const exportData = selectedOrders.value.map(order => ({
      '订单号': order.orderId || order.orderNo,
      '客户姓名': order.customerName,
      '客户电话': order.customerPhone,
      '服务类型': order.serviceType,
      '订单金额': `¥${order.totalAmount || order.actualAmount}`,
      '订单状态': getStatusText(order.status),
      '下单时间': order.createTime || order.createdTime,
      '取件地址': order.pickupAddress || order.receiverAddress,
      '备注': order.specialNote || order.remark || '无'
    }))

    // 转换为CSV格式
    const headers = Object.keys(exportData[0])
    const csvContent = [
      headers.join(','),
      ...exportData.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
    ].join('\n')

    // 创建下载链接
    const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `选中订单_${new Date().toISOString().slice(0, 10)}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success(`成功导出 ${selectedOrders.value.length} 个订单`)
  } catch (error) {
    console.error('批量导出订单失败:', error)
    ElMessage.error('批量导出订单失败')
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getOrderList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getOrderList()
}

// 分页处理
const handlePagination = (pagination) => {
  queryParams.pageNum = pagination.page
  queryParams.pageSize = pagination.limit
  getOrderList()
}

// 发货对话框相关数据
const shipDialogVisible = ref(false)
const shipSubmitting = ref(false)
const currentOrderId = ref('')
const shipFormRef = ref(null)
const shipForm = ref({
  logisticsCompany: '',
  trackingNumber: '',
  remark: ''
})

// 发货表单验证规则
const shipFormRules = {
  logisticsCompany: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNumber: [
    { required: true, message: '请输入物流单号', trigger: 'blur' },
    { min: 5, max: 32, message: '物流单号长度在 5 到 32 个字符', trigger: 'blur' }
  ]
}

// 订单详情相关
const orderDetailDialogVisible = ref(false)
const currentOrderDetail = ref(null)
const orderTimeline = ref([])
const orderLogistics = ref([])
const orderRemark = ref('')

// 加载订单时间线
const loadOrderTimeline = async (orderId) => {
  try {
    const response = await getOrderTimeline(orderId)
    if (response.code === 200) {
      orderTimeline.value = response.data || []
    } else {
      throw new Error(response.message || '获取订单时间线失败')
    }
  } catch (error) {
    console.error('获取订单时间线失败:', error)
    orderTimeline.value = []
  }
}

// 加载物流信息
const loadOrderLogistics = async (orderId) => {
  try {
    const response = await getOrderLogistics(orderId)
    if (response.code === 200) {
      orderLogistics.value = response.data || []
    } else {
      throw new Error(response.message || '获取物流信息失败')
    }
  } catch (error) {
    console.error('获取物流信息失败:', error)
    orderLogistics.value = []
  }
}

// 更新订单备注
const updateRemark = async () => {
  if (!currentOrderDetail.value) return

  try {
    const response = await updateOrderRemark(
      currentOrderDetail.value.id || currentOrderDetail.value.orderId,
      orderRemark.value
    )

    if (response.code === 200) {
      currentOrderDetail.value.remark = orderRemark.value
      ElMessage.success('备注更新成功')
    } else {
      throw new Error(response.message || '更新备注失败')
    }
  } catch (error) {
    console.error('更新备注失败:', error)
    ElMessage.error(error.message || '更新备注失败')
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取状态流转按钮类型
const getTransitionButtonType = (status) => {
  const typeMap = {
    [ORDER_STATUS.ACCEPTED]: 'primary',
    [ORDER_STATUS.PAID]: 'success',
    [ORDER_STATUS.PICKUP_STARTED]: 'primary',
    [ORDER_STATUS.PICKUP_COMPLETED]: 'success',
    [ORDER_STATUS.PROCESSING]: 'primary',
    [ORDER_STATUS.QUALITY_CHECK]: 'info',
    [ORDER_STATUS.DELIVERY_STARTED]: 'primary',
    [ORDER_STATUS.DELIVERED]: 'success',
    [ORDER_STATUS.COMPLETED]: 'success',
    [ORDER_STATUS.CANCELLED]: 'danger',
    [ORDER_STATUS.REFUNDED]: 'warning'
  }
  return typeMap[status] || 'default'
}

// 获取状态流转按钮文本
const getTransitionButtonText = (status) => {
  const textMap = {
    [ORDER_STATUS.ACCEPTED]: '接受订单',
    [ORDER_STATUS.PAID]: '确认付款',
    [ORDER_STATUS.PICKUP_STARTED]: '开始取件',
    [ORDER_STATUS.PICKUP_COMPLETED]: '确认取件',
    [ORDER_STATUS.PROCESSING]: '开始洗护',
    [ORDER_STATUS.QUALITY_CHECK]: '开始质检',
    [ORDER_STATUS.DELIVERY_STARTED]: '开始配送',
    [ORDER_STATUS.DELIVERED]: '确认送达',
    [ORDER_STATUS.COMPLETED]: '完成订单',
    [ORDER_STATUS.CANCELLED]: '取消订单',
    [ORDER_STATUS.REFUNDED]: '申请退款'
  }
  return textMap[status] || '操作'
}

// 处理状态流转
const handleStatusTransition = async (targetStatus) => {
  if (!currentOrderDetail.value) return

  try {
    let confirmText = `确认将订单状态更改为"${getStatusText(targetStatus)}"？`
    let inputRequired = false
    let inputPlaceholder = ''

    // 根据目标状态设置不同的确认文本和输入要求
    switch (targetStatus) {
      case ORDER_STATUS.ACCEPTED:
        confirmText = '确认接受订单？'
        break
      case ORDER_STATUS.PAID:
        confirmText = '确认客户已付款？'
        break
      case ORDER_STATUS.PICKUP_STARTED:
        confirmText = '确认开始取件？'
        break
      case ORDER_STATUS.PICKUP_COMPLETED:
        confirmText = '确认取件完成？'
        break
      case ORDER_STATUS.PROCESSING:
        confirmText = '确认开始洗护？'
        break
      case ORDER_STATUS.QUALITY_CHECK:
        confirmText = '确认开始质检？'
        break
      case ORDER_STATUS.DELIVERY_STARTED:
        confirmText = '确认开始配送？'
        break
      case ORDER_STATUS.DELIVERED:
        confirmText = '确认已送达？'
        break
      case ORDER_STATUS.COMPLETED:
        confirmText = '确认完成订单？'
        break
      case ORDER_STATUS.CANCELLED:
        confirmText = '确认取消订单？'
        inputRequired = true
        inputPlaceholder = '请输入取消原因'
        break
      case ORDER_STATUS.REFUNDED:
        confirmText = '确认申请退款？'
        inputRequired = true
        inputPlaceholder = '请输入退款原因'
        break
    }

    let result
    if (inputRequired) {
      result = await ElMessageBox.prompt(confirmText, '状态变更', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputPlaceholder,
        inputValidator: (value) => {
          if (!value || value.trim().length === 0) {
            return '请输入原因'
          }
          return true
        }
      })
    } else {
      await ElMessageBox.confirm(confirmText, '状态变更', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      })
    }

    // 根据不同状态调用不同的API
    let response
    const orderId = currentOrderDetail.value.id || currentOrderDetail.value.orderId
    const reason = result?.value

    switch (targetStatus) {
      case ORDER_STATUS.ACCEPTED:
        response = await acceptOrder(orderId)
        break
      case ORDER_STATUS.PAID:
        response = await confirmPayment(orderId)
        break
      case ORDER_STATUS.PICKUP_STARTED:
        response = await startPickup(orderId)
        break
      case ORDER_STATUS.PICKUP_COMPLETED:
        response = await confirmPickup(orderId)
        break
      case ORDER_STATUS.PROCESSING:
        response = await startProcessing(orderId)
        break
      case ORDER_STATUS.QUALITY_CHECK:
        response = await completeProcessing(orderId)
        break
      case ORDER_STATUS.DELIVERY_STARTED:
        response = await startDelivery(orderId)
        break
      case ORDER_STATUS.DELIVERED:
        response = await confirmDelivery(orderId)
        break
      case ORDER_STATUS.COMPLETED:
        response = await completeOrder(orderId)
        break
      case ORDER_STATUS.CANCELLED:
        response = await cancelOrder(orderId, { reason })
        break
      case ORDER_STATUS.REFUNDED:
        response = await requestRefund(orderId, { reason })
        break
      default:
        // 通用状态更新
        response = await updateOrderStatus(orderId, {
          status: targetStatus,
          remark: reason || `状态变更为${getStatusText(targetStatus)}`
        })
    }

    if (response.code === 200) {
      currentOrderDetail.value.status = targetStatus
      ElMessage.success('状态更新成功')
      await getOrderList()
      await getOrderStatsData()
      await loadOrderTimeline(orderId)
    } else {
      throw new Error(response.message || '状态更新失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态流转失败:', error)
      ElMessage.error(error.message || '状态流转失败')
    }
  }
}

// 处理发货（已在上面定义，删除重复定义）

// 重置发货表单
const resetShipForm = () => {
  if (shipFormRef.value) {
    shipFormRef.value.resetFields()
  }
  shipForm.value = {
    logisticsCompany: '',
    trackingNumber: '',
    remark: ''
  }
  currentOrderId.value = ''
  shipSubmitting.value = false
}

// 提交发货表单
const submitShipForm = async () => {
  if (!shipFormRef.value) return

  await shipFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        shipSubmitting.value = true

        const response = await updateOrderStatus(currentOrderId.value, {
          status: ORDER_STATUS.SHIPPED,
          logisticsCompany: shipForm.value.logisticsCompany,
          trackingNumber: shipForm.value.trackingNumber,
          remark: shipForm.value.remark
        })

        if (response.code === 200) {
          ElMessage.success('发货成功')
          shipDialogVisible.value = false
          resetShipForm()
          await getOrderList()
        }
      } catch (error) {
        console.error('发货失败:', error)
        ElMessage.error('发货失败')
      } finally {
        shipSubmitting.value = false
      }
    }
  })
}



// 自动刷新定时器
let autoRefreshTimer = null
let lastOrderCount = 0

// 检查新订单
const checkNewOrders = (newOrderList) => {
  if (lastOrderCount > 0 && newOrderList.length > lastOrderCount) {
    const newOrdersCount = newOrderList.length - lastOrderCount
    ElMessage({
      message: `您有 ${newOrdersCount} 个新订单！`,
      type: 'success',
      duration: 5000,
      showClose: true
    })

    // 播放提示音（如果浏览器支持）
    try {
      const audio = new Audio('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBSuBzvLZiTYIG2m98OScTgwOUarm7blmGgU7k9n1unEiBC13yO/eizEIHWq+8+OWT')
      audio.play().catch(() => {
        // 忽略播放失败
      })
    } catch (error) {
      // 忽略音频错误
    }
  }
  lastOrderCount = newOrderList.length
}

// 开始自动刷新
const startAutoRefresh = () => {
  // 每30秒自动刷新一次
  autoRefreshTimer = setInterval(async () => {
    const oldCount = orderList.value.length
    await getOrderList()
    await getOrderStatsData()

    // 检查新订单
    if (orderList.value.length > oldCount) {
      checkNewOrders(orderList.value)
    }
  }, 30000)
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (autoRefreshTimer) {
    clearInterval(autoRefreshTimer)
    autoRefreshTimer = null
  }
}

// 初始化
onMounted(async () => {
  // 首先尝试获取真实数据
  await getOrderStatsData()
  await getOrderList()

  // 开始自动刷新
  startAutoRefresh()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  /* 让内容紧贴右侧 */
  min-width: 0;
}

.filter-container {
  margin-bottom: 20px;
}

.tabs-container {
  margin-top: 20px;
}

.orders-empty {
  text-align: center;
  color: #999;
  font-size: 16px;
  padding: 60px 0 40px 0;
  background: #fff;
  border-radius: 8px;
  min-height: 200px;
}

/* 统计卡片样式 */
.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  overflow: hidden;
}

.stat-card.pending {
  border-left: 4px solid #e6a23c;
}

.stat-card.processing {
  border-left: 4px solid #409eff;
}

.stat-card.completed {
  border-left: 4px solid #67c23a;
}

.stat-card.urgent {
  border-left: 4px solid #f56c6c;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 20px;
  color: white;
}

.pending .stat-icon {
  background: #e6a23c;
}

.processing .stat-icon {
  background: #409eff;
}

.completed .stat-icon {
  background: #67c23a;
}

.urgent .stat-icon {
  background: #f56c6c;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

/* 客户信息样式 */
.customer-info {
  line-height: 1.4;
}

.customer-name {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 2px;
}

.customer-phone {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 2px;
}

.customer-address {
  font-size: 11px;
  color: #9ca3af;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 服务信息样式 */
.service-info {
  line-height: 1.4;
}

.service-type {
  margin-bottom: 4px;
}

.service-items {
  font-size: 13px;
  color: #374151;
  margin-bottom: 2px;
}

.service-note {
  font-size: 11px;
  color: #6b7280;
  font-style: italic;
}

/* 距离样式 */
.distance {
  color: #6b7280;
  font-size: 13px;
}

/* 时间样式 */
.time-urgent {
  color: #f56c6c;
  font-weight: bold;
}

.time-warning {
  color: #e6a23c;
  font-weight: bold;
}

.time-normal {
  color: #6b7280;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

/* 价格样式 */
.price {
  color: #f56c6c;
  font-weight: bold;
}

/* 对话框样式 */
.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}

/* 表格内容垂直居中 */
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

/* 状态标签样式 */
:deep(.el-tag) {
  margin: 0 2px;
}

/* 分页样式 */
.pagination-container {
  padding: 20px;
  text-align: right;
}

/* 批量操作样式 */
.batch-operations {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 0;
  margin-top: 10px;
  border-top: 1px solid #e5e7eb;
}

.batch-info {
  color: #6b7280;
  font-size: 14px;
  margin-right: 10px;
}

/* 快速筛选样式 */
.quick-filter-container {
  margin-bottom: 20px;
}

.quick-filter-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.quick-filter-buttons .el-button {
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 13px;
}

/* 搜索表单样式优化 */
.demo-form-inline .el-form-item {
  margin-bottom: 10px;
}

.demo-form-inline .el-form-item__label {
  font-weight: 500;
  color: #374151;
}

/* 订单详情对话框样式 */
.order-detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

/* 时间线样式优化 */
.el-timeline {
  padding-left: 0;
}

.el-timeline-item__timestamp {
  font-size: 12px;
  color: #909399;
}

/* 批量操作工具栏样式 */
.batch-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 16px;
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.toolbar-left .selected-count {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
}

.toolbar-right .el-button-group .el-button {
  border-radius: 0;
}

.toolbar-right .el-button-group .el-button:first-child {
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}

.toolbar-right .el-button-group .el-button:last-child {
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

/* 统计卡片点击效果 */
.stat-card.clickable {
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card.clickable:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-card.clickable:active {
  transform: translateY(0);
}

/* 高级筛选对话框样式 */
.el-slider {
  margin: 20px 0;
}

/* 批量操作栏样式 */
.batch-operations {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  margin-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.batch-info {
  font-size: 14px;
  color: #6b7280;
  font-weight: 500;
}

/* 响应式设计优化 */
@media (max-width: 768px) {
  .batch-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .toolbar-right {
    width: 100%;
  }

  .toolbar-right .el-button-group {
    width: 100%;
    display: flex;
  }

  .toolbar-right .el-button-group .el-button {
    flex: 1;
  }

  .batch-operations {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .stat-card.clickable:hover {
    transform: none;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .quick-filter-buttons {
    justify-content: center;
  }

  .batch-operations {
    flex-wrap: wrap;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .demo-form-inline {
    display: block;
  }

  .demo-form-inline .el-form-item {
    display: block;
    margin-bottom: 15px;
  }

  .quick-filter-buttons .el-button {
    flex: 1;
    min-width: 120px;
  }
}
</style>